package cn.hsw.platform.core.configure;

import cn.hsw.platform.core.api.SnowFlakeApi;
import cn.hsw.platform.core.dto.ResultDto;
import cn.hsw.platform.core.util.SpringContextUtil;
import cn.hutool.core.util.RandomUtil;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;

import java.io.Serializable;

/**
 * 雪花ID生成
 * @author 李子木
 * @date 2020-11-05
 */
public class SnowFlakeIdGeneratorConfig implements IdentifierGenerator {

    @Override
    public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws HibernateException {

        SnowFlakeApi api = SpringContextUtil.getBean(SnowFlakeApi.class);
        ResultDto<Long> resultDto = api.generate();
        if(resultDto.isSuccess()){
            return resultDto.getData();
        }else {
            return RandomUtil.randomLong(1000000000L,1000000000000L);
        }
    }
}
